package com.dd.keel.core.common.shutdown;

import java.io.*;
import java.net.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dd.keel.core.common.shutdown.protocol.ShutdownProtocol;


public class ShutdownClient {
	
	final static private Logger LOGGER = LoggerFactory.getLogger(ShutdownClient.class);
	
	int shutdown_port = 0;
	
	public ShutdownClient(int shutdown_port)
	{
		this.shutdown_port = shutdown_port;
	}
	
	public void shutdown()
	{
        //send shutdown message
        Socket kkSocket = null;
        PrintWriter out = null;
        BufferedReader in = null;
        try {
        	System.out.println("access shutdown port "+shutdown_port);
            kkSocket = new Socket("localhost", shutdown_port);
            out = new PrintWriter(kkSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
        } catch (UnknownHostException ex) {
        	LOGGER.error(ex.getMessage(), ex);
            System.exit(1);
        } catch (IOException ex) {
        	LOGGER.error(ex.getMessage(), ex);
            System.exit(1);
        }
        
        String fromServer;
        try{
        	out.println(ShutdownProtocol.SHUTDOWN_REQUEST_MESSAGE);
            if ( (fromServer = in.readLine() ) != null ) {
            	System.out.println("From server: " + fromServer);
            }
        }catch(Exception ex){
        	LOGGER.error(ex.getMessage(), ex);
        }
        
        try{
            out.close();
        }catch(Exception ex){
        	LOGGER.error(ex.getMessage(), ex);
        }
        try{
            in.close();
        }catch(Exception ex){
        	LOGGER.error(ex.getMessage(), ex);
        }
        try{
            kkSocket.close();
        }catch(Exception ex){
        	LOGGER.error(ex.getMessage(), ex);
        }
        
	}
	
}
